/*
 * BspClient.as
 *
 * Copyright (C) 2011 - Dr.NP
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */

package bsp
{
	import bsp.net.TcpClient;
	
	import bsp.protocol.Luabase;
	import bsp.protocol.Raw;
	
	public class BspClient
	{
		private var conn : TcpClient;
		private var protocol : Object;
		
		// Default values
		private const DEFAULT_ADDR					: String = "localhost";
		private const DEFAULT_PORT					: uint = 60000;
		private const DEFAULT_PROTOCOL				: String = "Luabase";
		private const PROTOCOLS						: Object = {
			Luabase : Luabase, 
			Raw : Raw
		};
		
		// Contruct
		public function BspClient(param : Object)
		{
			// You do not give me anything
			if (!param.addr)
			{
				param.addr = DEFAULT_ADDR;
			}
			
			if (!param.port)
			{
				param.port = DEFAULT_PORT;
			}
			
			if (!param.protocol)
			{
				param.protocol = DEFAULT_PROTOCOL;
			}
			
			// OK, let's go
			this.conn = new TcpClient(param.addr, param.port);
			if (param.on_connect)
			{
				this.conn.on_connect = param.on_connect;
			}
			
			if (param.on_close)
			{
				this.conn.on_close = param.on_close;
			}
			
			if (param.on_io_error)
			{
				this.conn.on_io_error = param.on_io_error;
			}
			
			if (param.on_sec_error)
			{
				this.conn.on_sec_error = param.on_sec_error;
			}
			
			if (param.on_cmd)
			{
				this.conn.on_cmd = param.on_cmd;
			}
			
			// Prefer the protocol
			if (this.PROTOCOLS[param.protocol])
			{
				this.protocol = new this.PROTOCOLS[param.protocol]();
				this.conn.on_data = this.protocol.hrecv;
			}
			
			return;
		}
		
		public function send(cmd_id : uint, params : Object) : uint
		{
			var len : uint;
			len = this.conn.send(this.protocol.hsend(cmd_id, params));
			
			return len;
		}
		/*
		// Callback functions
		private function _f_on_connect() : void
		{
			return;
		}
		
		private function _f_on_close() : void
		{
			return;
		}
		
		private function _f_on_io_error() : void
		{
			return;
		}
		
		private function _f_on_sec_error() : void
		{
			return;
		}
		
		private function _f_on_data() : void
		{
			return;
		}
		*/
	}
}